<?php
namespace wechat;

/**
 * 微信接口方法
 */

class Wechat
{
    //发送公众号消息
    public function pushMsg($openid,$temp_id,$param){

        foreach ($param as $k=>$v){
            $Data[$k] = ['value'=>$v['val'], 'color'=>$v['color']];
        }

        $data=[
            "touser"=>$openid, //对方的openid，前一步获取
            "template_id"=>$temp_id, //模板id
            "url"=>'https://kf.sylwtech.cn/staff',//跳转客服聊天页面
            'topcolor'=>'#FF0000',
            "data"=>$Data
        ];

        $access_token = $this->getAccessToken();
        $requrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token; // 发送模板消息接口
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $requrl);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;

    }

    //获取公众号模版消息列表
    public function getTempList(){
        $url = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=".$this->getAccessToken();
        $rst = reqUrl($url);
        $rst = $rst['template_list'];
        return $rst;
    }

    //获取access_token
    public function getAccessToken() {
        // access_token 存到wechart配置文件
        $data = config('conf.');

        if ($data['gzh_expire_time'] < time()) {

            $url = 'https://api.weixin.qq.com/cgi-bin/token';
            $url .= '?grant_type=client_credential&appid='.config('conf.gzh_appid').'&secret='.config('conf.gzh_secret');
            $res = reqUrl($url);
            $access_token = $res['access_token'];
            if ($access_token) {
                $data['gzh_expire_time'] = time() + 7000;
                $data['gzh_access_token'] = $access_token;
                upConfig($data);
            }
        } else {
            $access_token = $data['gzh_access_token'];
        }

        return $access_token;
    }
}
